package com.example.excelimport.controller;

import com.example.excelimport.config.FilePathConfig;
import com.example.excelimport.service.UserService;
import com.example.excelimport.util.FileUtil;
import com.example.excelimport.util.MillionDataGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/excel")
@Slf4j
public class ExcelImportController {

    @Autowired
    private UserService userService;

    @Autowired
    private MillionDataGenerator dataGenerator;

    @Autowired
    private FilePathConfig filePathConfig;

    /**
     * 保存上传文件 - 修正版本
     */
    private String saveUploadFile(MultipartFile file) throws IOException {
        // 使用系统临时目录，避免路径问题
        String tempDir = System.getProperty("java.io.tmpdir");
        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();

        // 确保文件名安全
        fileName = fileName.replaceAll("[^a-zA-Z0-9._-]", "_");

        Path tempPath = Paths.get(tempDir, fileName);

        log.info("保存上传文件到: {}", tempPath.toString());

        // 确保目录存在
        Files.createDirectories(tempPath.getParent());

        // 保存文件
        file.transferTo(tempPath.toFile());

        return tempPath.toString();
    }

    /**
     * 生成百万数据Excel文件
     */
    @PostMapping("/generate/million")
    public ResponseEntity<Map<String, Object>> generateMillionData() {
        try {
            String filePath = dataGenerator.generateMillionData();

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "百万数据Excel生成成功");
            result.put("filePath", filePath);
            result.put("fileSize", getFileSize(filePath));

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("生成Excel失败", e);
            return ResponseEntity.status(500).body(createErrorResult("生成失败: " + e.getMessage()));
        }
    }
    private String getFileSize(String filePath) {
        try {
            long size = Files.size(Paths.get(filePath));
            if (size < 1024) {
                return size + " B";
            } else if (size < 1024 * 1024) {
                return String.format("%.2f KB", size / 1024.0);
            } else {
                return String.format("%.2f MB", size / (1024.0 * 1024.0));
            }
        } catch (IOException e) {
            return "未知";
        }
    }


    /**
     * 方法一：监听器模式导入 - 修正版本
     */
    @PostMapping("/import/listener")
    public ResponseEntity<Map<String, Object>> importByListener(@RequestParam("file") MultipartFile file) {
        String tempFilePath = null;
        try {
            // 检查文件
            if (file == null || file.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResult("文件不能为空"));
            }

            // 保存文件
            tempFilePath = saveUploadFile(file);
            log.info("开始导入文件: {}，临时路径: {}", file.getOriginalFilename(), tempFilePath);

            // 检查文件是否存在
            if (!Files.exists(Paths.get(tempFilePath))) {
                return ResponseEntity.badRequest().body(createErrorResult("文件保存失败"));
            }

            // 执行导入
            userService.importByListener(tempFilePath);

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "监听器模式导入成功");
            result.put("fileName", file.getOriginalFilename());

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("导入失败", e);
            return ResponseEntity.status(500).body(createErrorResult("导入失败: " + e.getMessage()));
        } finally {
            // 清理临时文件
            if (tempFilePath != null) {
                try {
                    Files.deleteIfExists(Paths.get(tempFilePath));
                } catch (IOException e) {
                    log.warn("删除临时文件失败: {}", tempFilePath, e);
                }
            }
        }
    }


    /**
     * 清除所有用户数据
     */
    @DeleteMapping("/clear/all")
    public ResponseEntity<Map<String, Object>> clearAllData() {
        try {
            long count = userService.clearAllData();

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "数据清除成功");
            result.put("deletedCount", count);

            log.info("清除所有用户数据，共 {} 条记录", count);
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("清除数据失败", e);
            return ResponseEntity.status(500).body(createErrorResult("清除数据失败: " + e.getMessage()));
        }
    }

    /**
     * 重置自增ID（TRUNCATE TABLE）
     * 注意：这会删除所有数据并重置自增ID为1
     */
    @DeleteMapping("/clear/reset")
    public ResponseEntity<Map<String, Object>> resetTable() {
        try {
            userService.resetTable();

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "表重置成功，自增ID已重置");

            log.info("用户表重置成功");
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("表重置失败", e);
            return ResponseEntity.status(500).body(createErrorResult("表重置失败: " + e.getMessage()));
        }
    }

    /**
     * 获取数据统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getDataStats() {
        try {
            Map<String, Object> stats = userService.getDataStats();

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", stats);

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("获取统计信息失败", e);
            return ResponseEntity.status(500).body(createErrorResult("获取统计信息失败: " + e.getMessage()));
        }
    }

    /**
     * 清理临时文件目录
     */
    @DeleteMapping("/clear/temp-files")
    public ResponseEntity<Map<String, Object>> clearTempFiles() {
        try {
            String tempDir = filePathConfig.getTempDir();
            long deletedCount = FileUtil.clearDirectory(tempDir, ".xlsx");

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "临时文件清理成功");
            result.put("deletedCount", deletedCount);
            result.put("directory", tempDir);

            log.info("清理临时文件目录，共删除 {} 个文件", deletedCount);
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("清理临时文件失败", e);
            return ResponseEntity.status(500).body(createErrorResult("清理临时文件失败: " + e.getMessage()));
        }
    }

    /**
     * 文件上传测试接口
     */
    @PostMapping("/upload-test")
    public ResponseEntity<Map<String, Object>> uploadTest(@RequestParam("file") MultipartFile file) {
        String tempFilePath = null;
        try {
            if (file == null || file.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResult("文件不能为空"));
            }

            tempFilePath = saveUploadFile(file);

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "文件上传测试成功");
            result.put("fileName", file.getOriginalFilename());
            result.put("fileSize", file.getSize());
            result.put("tempPath", tempFilePath);
            result.put("fileExists", Files.exists(Paths.get(tempFilePath)));

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("上传测试失败", e);
            return ResponseEntity.status(500).body(createErrorResult("上传测试失败: " + e.getMessage()));
        } finally {
            if (tempFilePath != null) {
                try {
                    Files.deleteIfExists(Paths.get(tempFilePath));
                } catch (IOException e) {
                    log.warn("删除临时文件失败: {}", tempFilePath, e);
                }
            }
        }
    }

    private Map<String, Object> createErrorResult(String message) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", message);
        return result;
    }
}
